<!--
 * @Description: 
 * @Author: william
 * @Date: 2024-09-10 09:09:28
 * @LastEditors: william
 * @LastEditTime: 2024-10-24 19:15:06
-->
<template>
  <uv-calendars
    ref="calendarsEl"
    :insert="false"
    mode="range"
    allowSameDay
    :startText="$t('public.start')"
    :endText="$t('public.end')"
    :startDate="minDate"
    :endDate="maxDate"
    :date="date"
    @startChange="handleCalendarsStartChange"
    @confirm="handleCalendarsConfirm"
  ></uv-calendars>
</template>

<script setup>
defineOptions({
  name: 'Calendars',
  inheritAttrs: false
})

const props = defineProps({
  date: {
    type: [Array, String],
    default: () => [
      g_dayjs().format('YYYY-MM-DD'),
      g_dayjs().format('YYYY-MM-DD')
    ]
  },
  // 限制天数，默认30天
  limitDays: {
    type: [Number, String],
    default: '30'
  }
})

// 时间范围参数
const calendarsEl = ref(null)
const minDate = ref('')
const maxDate = ref(g_dayjs().format('YYYY-MM-DD'))

const emit = defineEmits(['confirm'])

onMounted(_ => {})

const open = _ => {
  calendarsEl.value.open()
}

const close = _ => {
  calendarsEl.value.close()
}

// 最多选择一个月的时间
const calcMinDate = e => {
  const one = props.limitDays * 24 * 3600 * 1000
  const todayMaxTime = g_dayjs().endOf('day').valueOf()
  const minTime = g_dayjs(e.fulldate).endOf('day').valueOf() - one
  let maxTime = g_dayjs(e.fulldate).startOf('day').valueOf() + one
  if (maxTime > todayMaxTime) maxTime = todayMaxTime
  minDate.value = g_dayjs(minTime).format('YYYY-MM-DD')
  maxDate.value = g_dayjs(maxTime).format('YYYY-MM-DD')
}

const handleCalendarsStartChange = e => {
  calcMinDate(e)
}
const handleCalendarsConfirm = e => {
  const range = e.range
  emit('confirm', {
    startTime: range.before + ' 00:00:00',
    endTime: range.after + ' 23:59:59',
    date: [range.before, range.after]
  })
}

defineExpose({
  open,
  close
})
</script>

<style lang="scss" scoped></style>
